package com.qf.sportsevent.util;

import android.content.Context;
import android.databinding.BindingAdapter;
import android.databinding.InverseBindingListener;
import android.databinding.InverseBindingMethod;
import android.databinding.InverseBindingMethods;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.qf.sportsevent.R;

import java.util.List;

import static android.view.View.GONE;


/**
 * Created by Administrator on 2016/12/15.
 */
@InverseBindingMethods(
        {
                @InverseBindingMethod(type = ViewPager.class,attribute = "currentItem",method = "getCurrentItem")
        }
)
public class MyBindings {
    @BindingAdapter({"fragmentList","fragmentManager"})
    public static void initRadioGroup(RadioGroup radioGroup,
                                                   final List<Fragment> fragmentList,
                                                   final FragmentManager manager){
        for (int i = 0; i < radioGroup.getChildCount(); i++) {
            radioGroup.getChildAt(i).setId(i);
        }
        radioGroup.check(0);

        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(R.id.main_frame,fragmentList.get(0));
        transaction.commit();

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.replace(R.id.main_frame,fragmentList.get(i));
                transaction.commit();
            }
        });
    }

    @BindingAdapter({"radioCount","radioLayout"})
    public static void setViewPagerPoint(RadioGroup radioGroup,int radioCount,int radioLayoutId){
        if (radioGroup.getChildCount()>0) {
            radioGroup.removeAllViews();
        }
        Context context = radioGroup.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);
        RadioGroup.LayoutParams layoutParams=new RadioGroup.LayoutParams( RadioGroup.LayoutParams.WRAP_CONTENT,RadioGroup.LayoutParams.WRAP_CONTENT);
        int margin= (int) context.getResources().getDimension(R.dimen.radio_button_margin);
        layoutParams.setMargins(margin,0,margin,0);
        for (int i = 0; i < radioCount; i++) {
            View view = inflater.inflate(radioLayoutId, null);
            view.setLayoutParams(layoutParams);
            view.setId(i);
            radioGroup.addView(view);
        }
    }

    @BindingAdapter({"loadImgByUrl","imageType"})
    public static void loadImage(ImageView imageView,String imgUrl,int imageType){
        if(imgUrl!=null&& !TextUtils.isEmpty(imgUrl)){
            switch (imageType) {
                case 0:
                    imgUrl=UrlManager.getCommonImageUrl(imgUrl);
                    break;
                case 1:
                    imgUrl=UrlManager.getThreeImageUrl(imgUrl);
                    break;
                case 2:
                    imgUrl=UrlManager.getViewPagerImageUrl(imgUrl);
                    break;
                case 3:
                    imgUrl=UrlManager.getViewPagerImageUrl(imgUrl);
                    break;
                case 4:
                    imgUrl=UrlManager.getLogoUrl(imgUrl);
            }
            Glide.with(imageView.getContext()).load(imgUrl).into(imageView);
        }
    }

    @BindingAdapter(value = {"commentNum","labelName","isTop"},requireAll = false)
    public static void setCommentNum(TextView textView,int commentNum,String labelName,boolean isTop){
        if(commentNum!=0){
            textView.setText(commentNum+"评");
        }else if(labelName!=null){
            textView.setText(labelName);
        }else if(isTop){
            textView.setText("头条");
        }else{
            textView.setVisibility(GONE);
        }
    }

    @BindingAdapter("playIconVisibility")
    public static void setPlayIconVisibility(ImageView playIcon,String videoLink){
        if(videoLink!=null&&!TextUtils.isEmpty(videoLink)){
            playIcon.setVisibility(View.VISIBLE);
            playIcon.bringToFront();
        }else{
            playIcon.setVisibility(View.GONE);
        }
    }

    @BindingAdapter({"time","user"})
    public static void setDetailItemTime(TextView textView,String time,String user){
        String date = FormatUtils.formatMonthDayTime(time);
        if(date!=null) {
            String s = date + "\t\t\t" + user;
            textView.setText(s);
        }
    }

    @BindingAdapter({"content","imageUrls"})
    public static void setNewsContent(LinearLayout layout,String content,List<String> imageUrls){
        if(content!=null&&!TextUtils.isEmpty(content)) {
            String[] strings = content.split("\\$\\{lx-br\\}");
            if(layout.getChildCount() == strings.length){
                return;
            }
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            Context context = layout.getContext();
            for (int i = 0; i < strings.length; i++) {
                if (strings[i].contains("lx-image")) {
                    if(imageUrls!=null&&imageUrls.size()>0) {
                        int index = strings[i].lastIndexOf("-");
                        int imgIndex = Integer.parseInt(strings[i].substring(index+1, index + 2));
                        ImageView imageView = new ImageView(context);
                        Glide.with(context).load(imageUrls.get(imgIndex)).into(imageView);
                        imageView.setLayoutParams(params);
                        layout.addView(imageView);
                    }
                } else {
                    TextView textView = new TextView(context);
                    textView.setText("\t\t"+strings[i]);
                    textView.setTextColor(Color.BLACK);
                    textView.setTextSize(16f);
                    textView.setLineSpacing(8,1);
                    layout.addView(textView);
                }
            }
        }
    }

    @BindingAdapter("keepScroll")
    public static void setKeepScroll(final ViewPager viewPager, final boolean keepScroll){
        viewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        viewPager.requestDisallowInterceptTouchEvent(keepScroll);
                        break;
                        }
                return false;
                }
        });
    }



    @BindingAdapter("currentItem")
    public static void setCurrentItem(ViewPager pager, int item) {
        pager.setCurrentItem(item);
    }

    @BindingAdapter("currentItemAttrChanged")
    public static void setCurrentItemChanged(ViewPager pager, final InverseBindingListener listener) {
            pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    listener.onChange();
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
    }

    @BindingAdapter("autoPlayDelayed")
    public static void setAutoPlayDelayed(final ViewPager pager, final int delay){
        Handler handler = (Handler) pager.getTag();
        if(handler == null){
            handler = new Handler(Looper.getMainLooper()){
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    if(msg.what == 0){
                        int index = pager.getCurrentItem() + 1;
                        if(index >= pager.getAdapter().getCount()){
                            index = 0;
                        }
                        pager.setCurrentItem(index);
                        sendEmptyMessageDelayed(0,delay);
                    }
                }
            };
            pager.setTag(handler);
        }
        handler.removeMessages(0);
        if(delay > 0){
            handler.sendEmptyMessageDelayed(0,delay);
        }
    }

}


